package com.example.myproject.service.impl;

import com.example.myproject.dto.CommentReportDTO;
import com.example.myproject.dto.comment.CommentsListResponse;
import com.example.myproject.dto.report.ReportRequest;
import com.example.myproject.dto.report.ReportResponse;
import com.example.myproject.mapper.CommentMapper;
import com.example.myproject.mapper.CommentReportMapper;
import com.example.myproject.mapper.UserMapper;
import com.example.myproject.model.Comment;
import com.example.myproject.model.CommentReport;
import com.example.myproject.security.JwtAuthenticationFilter;
import com.example.myproject.service.ReportService;
import com.example.myproject.service.UserService;
import com.example.myproject.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private CommentReportMapper commentReportMapper;
    
    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public ReportResponse reportComment(Long commentId, ReportRequest req) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = null;
        if (auth.getPrincipal() instanceof JwtAuthenticationFilter.UserPrincipal) {
            userId = ((JwtAuthenticationFilter.UserPrincipal) auth.getPrincipal()).getId();
        } else {
            throw new IllegalStateException("Unexpected principal type");
        }
        // 检查是否已经举报过
        if (commentReportMapper.existsByCommentIdAndUserId(commentId, userId) > 0) {
            throw new IllegalStateException("您已经举报过该评论");
        }
        
        // 获取用户信息
        UserInfoVO userInfo = userService.getUserInfo(userId);
        if (userInfo == null) {
            throw new IllegalStateException("无法获取用户信息");
        }
        
        // 创建举报记录
        CommentReport report = new CommentReport();
        report.setCommentId(commentId);
        report.setUserId(userId);
        report.setReason(req.getReason());
        report.setStatus("pending"); // 初始状态为待处理
        report.setCreateTime(LocalDateTime.now());
        
        // 保存举报记录
        commentReportMapper.insert(report);
        
        // 构建响应
        ReportResponse resp = new ReportResponse();
        resp.setReport_id(report.getReportId());
        resp.setComment_id(Math.toIntExact(commentId));
        resp.setStatus(report.getStatus());
        resp.setReported_at(report.getCreateTime().toString());
        
        // 设置用户信息
        resp.setUser_id(userInfo.getUserId().intValue());
        resp.setUsername(userInfo.getUserName());
        resp.setAvatar_url(userInfo.getAvatarUrl());
        
        return resp;
    }
    
    @Transactional
    public ReportResponse updateReportStatus(Integer reportId, String status) {
        // 更新举报状态
        if (commentReportMapper.updateStatus(reportId, status) > 0) {
            // 查询更新后的举报记录并返回
            CommentReport report = commentReportMapper.selectById(reportId);
            if (report != null) {
                UserInfoVO userInfo = userService.getUserInfo(report.getUserId());
                
                ReportResponse resp = new ReportResponse();
                resp.setReport_id(report.getReportId());
                resp.setComment_id(Math.toIntExact(report.getCommentId()));
                resp.setStatus(report.getStatus());
                resp.setReported_at(report.getCreateTime().toString());
                
                // 设置用户信息
                resp.setUser_id(userInfo.getUserId().intValue());
                resp.setUsername(userInfo.getUserName());
                resp.setAvatar_url(userInfo.getAvatarUrl());
                
                return resp;
            }
        }
        throw new IllegalStateException("更新举报状态失败");
    }


    @Autowired
    private UserMapper userMapper;





    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<CommentReportDTO> getPendingReports() {
        List<Map<String, Object>> rawList = commentReportMapper.selectPendingReports();
        List<CommentReportDTO> result = new ArrayList<>();
        for (Map<String, Object> map : rawList) {
            CommentReportDTO dto = new CommentReportDTO();
            dto.setReportId((Long) map.get("report_id"));
            dto.setCommentId((Long) map.get("comment_id")); // 新增
            dto.setCommentContent((String) map.get("comment_content"));

            dto.setReportedUserId((Long) map.get("reported_user_id"));
            dto.setReportedUserName((String) map.get("reported_user_name"));
            dto.setReportedUserStatus((String) map.get("reported_user_status")); // 新增
            dto.setReason((String) map.get("reason"));
            dto.setCreateTime(map.get("create_time").toString());
            result.add(dto);
        }
        return result;
    }

    @Override
    @Transactional
    public void handleReportAndBanUser(Long reportId, Long userId, Long commentId) {
        // 1. 封禁用户
        userMapper.banUser(userId);
        // 2. 逻辑删除评论及其所有子评论
        markCommentAndChildrenDeleted(commentId);
        // 3. 批量更新所有该评论的举报为succeed
        commentReportMapper.markAllReportsSucceedByCommentId(commentId);
    }

    private void markCommentAndChildrenDeleted(Long commentId) {
        commentMapper.markDeleted(commentId);
        // 递归删除所有子评论
        List<Comment> children = commentMapper.findActiveChildren(commentId);
        for (Comment child : children) {
            markCommentAndChildrenDeleted(Long.valueOf(child.getCommentId()));
        }
    }

}